package com.ffapp.demo.chat;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisActivity;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.BaseListBeanXF;
import com.ffapp.demo.bean.BasisBean;
import com.ffapp.demo.bean.LoginBean;
import com.ffapp.demo.chat.model.ChatMsgListBean;
import com.ffapp.demo.chat.stomp.StompUtils;
import com.ffapp.demo.util.MyUtils;
import com.ffapp.demo.view.SizeChangeRelativeLayout;
import com.lzf.easyfloat.EasyFloat;
import com.lzf.easyfloat.enums.ShowPattern;
import com.lzf.easyfloat.enums.SidePattern;
import com.lzf.easyfloat.interfaces.OnInvokeView;

import butterknife.BindView;
import butterknife.OnClick;
import my.LogUtil;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;
import ua.naiksoftware.stomp.StompClient;

/**
 * 讨论组聊天记录
 */

public class GroupHistoryActivity extends BasisActivity {
    String TAG = StompUtils.TAG;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    private AdapterChat mAdapter;

    String alarmId;
    String address_host = "";

    ChatMsgListBean mMsgListBean;
    StompClient stompClient;

    ChatMsgListBean mListHistoryMsg;


    final static int MORE_MODE_DEFAULT = 0 ;
    private int more_mode = MORE_MODE_DEFAULT;

    public final String URL_SEND = "/api/v1/talkgroupMsg/send";

    @BindView(R.id.view_relatevelayout)
    SizeChangeRelativeLayout relativeLayout;
    @BindView(R.id.view_unreadmsg_count_zone)
    View view_unreadmsg_count_zone;
    @BindView(R.id.text_unread_msg_count)
    TextView text_unread_msg_count;
    @BindView(R.id.edit_search)
    TextView edit_search;

    private int mHistoryMsgCount;

    LinearLayoutManager mLinearLayoutManager;

    @Override
    public void initViews() {
        setDefautTrans(false);
        setContentView(R.layout.group_history_activity);
        setTitle("历史记录");
        setTitleLeftButton(null);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        recyclerview.setLayoutManager(mLinearLayoutManager);

        relativeLayout.setOnResizeListener(new SizeChangeRelativeLayout.OnResizeListener() {
            @Override
            public void onResize(int w, int h, int oldw, int oldh) {
                LogUtil.i("relativeLayout--->h" + h + "-----oldh---:" + oldh);
                if (h < oldh) {
                    scrollView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.smoothScrollBy(0, (oldh - h));
                        }
                    }, 100);


//                    scrollToTheBottom();
                }
//                scrollToTheBottom();
//                if (h < oldh) {
////                    scrollView.smoothScrollBy(0,(oldh-h));
//
//                }
            }
        });
        if(LoginBean.isLogin() && LoginBean.getInstance().getUserInfo().isUserCompany() ){
            EasyFloat.with(this)
                    // 设置浮窗xml布局文件，并可设置详细信息
                    .setLayout(R.layout.user_float_view, new OnInvokeView() {
                        @Override
                        public void invoke(View view) {
                            ((TextView)view.findViewById(R.id.float_text_name)).setText(LoginBean.getInstance().getUserInfo().getName() + MyUtils.getPhoneLastFour(mContext));
//                            ((TextView)view.findViewById(R.id.float_text_mobile)).setText(new MySharedPreferences(mContext).getUser());
                        }
                    })
                    // 设置浮窗显示类型，默认只在当前Activity显示，可选一直显示、仅前台显示、仅后台显示
                    .setShowPattern(ShowPattern.CURRENT_ACTIVITY)
                    // 设置吸附方式，共15种模式，详情参考SidePattern
                    .setSidePattern(SidePattern.DEFAULT)
                    // 设置浮窗的标签，用于区分多个浮窗
                    .setTag("float")
                    // 设置浮窗是否可拖拽，默认可拖拽
                    .setDragEnable(false)
                    // 系统浮窗是否包含EditText，仅针对系统浮窗，默认不包含
                    .hasEditText(false)
                    // 设置浮窗固定坐标，ps：设置固定坐标，Gravity属性和offset属性将无效
//                    .setLocation(100, 200)
                    // 设置浮窗的对齐方式和坐标偏移量
                    .setGravity(Gravity.BOTTOM | Gravity.RIGHT, -30, -150)
                    // 设置宽高是否充满父布局，直接在xml设置match_parent属性无效
                    .setMatchParent(false, false)
                    // 设置Activity浮窗的出入动画，可自定义，实现相应接口即可（策略模式），无需动画直接设置为null
                    .setAnimator(null)
                    // 设置系统浮窗的出入动画，使用同上
                    .setAppFloatAnimator(null)
                    // 设置系统浮窗的不需要显示的页面
                    .show();
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setNeedSign(false);
        super.initData(savedInstanceState);
        alarmId = getIntent().getStringExtra("id");
        if (TextUtils.isEmpty(alarmId)) {
            showToast("ID不存在");
            finish();
            return;
        }
        mMsgListBean = new ChatMsgListBean();
        setListView(false);

        address_host = MyUtils.getIp() + "/serv" + "/disposalsocket?type=talkgroup&alarmId=" + alarmId + "&userId=" + LoginBean.getUserId();
//        address_host = "ws://192.168.25.61:8012/disposalsocket?type=talkgroup&alarmId="+alarmId+"&userId="+ LoginBean.getUserId();
//        address_host = "http://192.168.25.61:8012/disposalsocket?type=talkgroup&alarmId="+alarmId+"&userId="+ LoginBean.getUserId();
//        address_host = MyUtils.getIp()+ ""+"/disposalsocket?type=talkgroup&alarmId="+alarmId+"&userId="+ LoginBean.getUserId();
        if (address_host.startsWith("http://192.") && address_host.contains("/serv/")) {
            address_host = address_host.replaceFirst("/serv/", "/");
        }

//        address_host = "ws://192.168.25.61:8012/disposalsocket";
//        address_host = "ws://121.40.165.18:8800";//http://www.websocket-test.com/测试用的websocket可连上
//        address_host = "ws://10.0.2.2:8080/example-endpoint/websocket";
        if(address_host.startsWith("http://")){
//            address_host = address_host.replace("http://","ws://");
        }
        if(address_host.startsWith("https://")){
            address_host = address_host.replace("https://","http://");
        }
        LogUtil.i(TAG, "address_host--->" + address_host);
//        initStom();


//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                getHistoryMsg(false);
//            }
//        }, 1000);

        getUnreadMsgCount();
        getHistoryMsg(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(stompClient != null && stompClient.isConnected()){
            stompClient.disconnect();
            stompClient = null;
        }
    }



    private void setListView(boolean isScrolltoBottom) {
        if (mAdapter == null) {
            mAdapter = new AdapterChat(mContext, mMsgListBean,mTopMoreClick);
            recyclerview.setAdapter(mAdapter);
        } else {
            mAdapter.setData(mMsgListBean);
        }
        if(isScrolltoBottom){
            scrollToTheBottom();
        }
    }
    AdapterChat.TopMoreClickListener mTopMoreClick = new AdapterChat.TopMoreClickListener() {
        @Override
        public void onTopMoreClick() {
            getHistoryMsg(true);
        }
    };


    void scrollToTheBottom() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        }, 100);

    }
    void scrollToTheTop() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_UP);
            }
        }, 100);

    }

    private static final int MSG_DISCONNECTED = 91;
    private static final int MSG_CONNECT_FAILED = 92;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (isFinishing()) return;
            switch (msg.what) {
                case MSG_DISCONNECTED:
                    if (stompClient.isConnected()) return;
                    break;
                case MSG_CONNECT_FAILED:
                    mHandler.removeMessages(MSG_CONNECT_FAILED);
                    mHandler.sendEmptyMessageDelayed(MSG_DISCONNECTED, 5000);
                    break;
            }
        }
    };


    void getHistoryMsg(boolean isMore) {

        MyParams params = new MyParams();
        params.put(BaseListBeanXF.PAGE_NAME, "1");
        params.put(BaseListBeanXF.PAGE_SIZE_NAME, ChatMsgListBean.ONE_PAGE_SIZE);
        if (mMsgListBean != null && mMsgListBean.getList().size() > 0) {
            params.put("endTime", mMsgListBean.getList().get(0).getCreateTime());
        }else {
            params.put("endTime", TimeUtils.getCurrentTimeByFormat(TimeUtils.TIME_FOMART));
        }
        params.put("alarmId", alarmId);
        params.put("type", "userstate");
        String key = edit_search.getText().toString().trim();
        if(!TextUtils.isEmpty(key)){
            params.put("keyWord", key);
        }
        showProgress();
        MyHttpUtils.post(Constants.URL_CHAT_HISTORY_MSG_BY_TYPE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        ChatMsgListBean bean = (ChatMsgListBean) result;
                        if(bean.getList().size() == 0){
                            if(isMore){
                                showToast("没有更多了");
                            }else {
                                showToast("无数据");
                            }
                        }else {
                            mMsgListBean.getList().addAll(0, bean.getList());
                            mMsgListBean.sortByCreateTime();
                            setListView(!isMore);
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        setListView(false);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, ChatMsgListBean.class);
    }

    @OnClick(R.id.img_search)
    void search() {
//        if (TextUtils.isEmpty(searchkey)) {
//            showToast(R.string.app_please_input_search_key);
//            return;fireCarApplication/getAllDrivers
//        }
        mMsgListBean.getList().clear();
        getHistoryMsg(false);
    }


    void getUnreadMsgCount() {
//        initStom();
        MyParams params = new MyParams();
            params.put("endTime", TimeUtils.getCurrentTimeByFormat(TimeUtils.TIME_FOMART));
        params.put("alarmId", alarmId);
        showProgress();
        MyHttpUtils.post(Constants.URL_CHAT_UNREAD_MSG_COUNT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        BasisBean bean = (BasisBean) result;
                        String msgCountStr = bean.getResultData();
                        mHistoryMsgCount = 0;
                        try {
                            mHistoryMsgCount = Integer.valueOf(msgCountStr);
                        }catch (Exception e){

                        }
                        if(mHistoryMsgCount == 0 || mHistoryMsgCount < 10){
                            view_unreadmsg_count_zone.setVisibility(View.GONE);
                        }else {
                            view_unreadmsg_count_zone.setVisibility(View.VISIBLE);
                            if(mHistoryMsgCount > 100){
                                text_unread_msg_count.setText(mHistoryMsgCount+"条新消息");
                            }else {
                                text_unread_msg_count.setText(mHistoryMsgCount+"条新消息");
                            }

                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        setListView(false);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, BasisBean.class);
    }

    @OnClick(R.id.view_unreadmsg_count_zone)
    void onUnReadMsgClick(){
        LogUtil.i("onUnReadMsgClick---->"+mHistoryMsgCount);
        view_unreadmsg_count_zone.setVisibility(View.GONE);
        if(mHistoryMsgCount > 0){
            int toPosition = 0;
            if(mMsgListBean.getList().size() < mHistoryMsgCount){
                toPosition = 0;
            }else {
                toPosition = mMsgListBean.getList().size() -mHistoryMsgCount;
            }
            if( mLinearLayoutManager.findViewByPosition(toPosition) != null){
                int scrollPosition =  mLinearLayoutManager.findViewByPosition(toPosition).getTop();
                //            LogUtil.i("scrollPosition---->"+scrollPosition);
//            LogUtil.i("scrollPosition---->"+mLinearLayoutManager.findViewByPosition(toPosition).getBottom());
                scrollView.scrollTo(0,scrollPosition);
            }
        }
    }


}
